<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button class="buttons" @click="handleCreate">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词:</label>
        <el-input v-model="listQuery.keyword" placeholder="关键词" class="filterInput" @keyup.enter.native="handleFilter" />
        <label class="filterLabel">是否显示:</label>
        <el-select v-model="listQuery.isshow" class="search-select" clearable placeholder="请选择">
          <el-option label="所有" :value="0" />
          <el-option label="显示" :value="1" />
          <el-option label="隐藏" :value="2" />
        </el-select>
        <el-button class="buttons" @click="handleFilter">
          搜索
        </el-button>
        <el-select v-model="excelType" class="fideselect" style="margin-left: 20px;" placeholder="导出Excel" :loading="downloadLoading" @change="handleExpload">
          <el-option label="当前页面" :value="1" />
          <el-option label="所有页面" :value="2" />
        </el-select>
      </div>
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      style="width: 100%;"
      :header-cell-style="{background:'#ebebeb',height:'#54px'}"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="景区ID" width="150px" align="center">
        <template slot-scope="{row}">
          <el-link :href="'/ynadmin/coupons/index?scenic_id='+row.scenic_id" title="点击跳转" type="warning">
            <span>
              {{ row.scenic_id }}
            </span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="景区名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" width="110px" align="center">
        <template slot-scope="{row}">
          <span><el-tag :type="row.isshow===1?'success':'danger'">{{ row.isshow_name }}</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="parseInt(row.isshow)===1" type="success" size="mini" @click="handleDetail(row)">
            查看二维码
          </el-button>
          <el-popconfirm
            v-if="false"
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="景区ID" prop="scenic_id">
          <el-input v-model="rows.scenic_id" :disabled="dialogStatus==='create'?false:true" placeholder="" />
        </el-form-item>
        <el-form-item label="景区名称" prop="name">
          <el-input v-model="rows.name" placeholder="" />
        </el-form-item>
        <!-- <el-form-item label="图片" prop="image">
          <uploadImg v-model="rows.image" />
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input v-model="rows.sort" type="number" placeholder="" />
        </el-form-item>
        <el-form-item label="跳转地址" prop="jump_url">
          <el-input v-model="rows.jump_url" type="text" placeholder="" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isshow">
          <el-radio v-model="rows.isshow" :label="1">显示</el-radio>
          <el-radio v-model="rows.isshow" :label="2">隐藏</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看二维码" :visible.sync="dialogDetailVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="detailInfo.name" prop="scenic_id">
          <a :href="detailInfo.code_url" :download="detailInfo.name" title="点击下载">
            <el-image :src="detailInfo.code_url" />
            下载二维码
          </a>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { search, getInfo, searchapi, add, edit } from '@/api/scenic'
// import uploadImg from '@/components/Upload/uploadImg'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { notifySuccess } from '@/utils/message'
import { parseTime } from '@/utils/index'
export default {
  name: 'AttachmentIndex',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      excelType: null,
      dialogDetailVisible: false,
      addFormVisible: false,
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        keyword: '',
        isshow: 0,
        sort: '+id'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: { 'normal': '正常', 'hidden': '隐藏' },
      showReviewer: false,
      rows: {
        id: null,
        image: null,
        scenic_id: null,
        name: '',
        isshow: '',
        status: 1,
        jump_url: '',
        sort: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        groupid: [{ required: true, message: '角色组不能为空', trigger: 'change' }],
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        // password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        realname: [{ required: true, message: '真实姓名', trigger: 'blur' }]
      },
      downloadLoading: false,
      detailInfo: {}// 详情
    }
  },
  created() {
    this.getSearchapi()
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      const kw = this.listQuery.keyword
      this.listQuery.keyword = kw.trim()
      this.listLoading = true
      search(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getSearchapi() {
      searchapi().then(res => {
        console.log(res)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        scenic_id: null,
        name: '',
        isshow: '',
        status: 1,
        jump_url: '',
        sort: ''
      }
    },
    handleCreate() {
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增提交方法
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            scenic_id: this.rows.scenic_id,
            name: this.rows.name,
            isshow: this.rows.isshow,
            status: this.rows.status,
            jump_url: this.rows.jump_url,
            sort: this.rows.sort
          }
          add(tempData).then(res => {
            that.dialogFormVisible = false
            that.getList()
            notifySuccess(res.msg || '添加成功')
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      getInfo(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑数据
    handleDetail(row) {
      const that = this
      getInfo(row.id).then(function(res) {
        that.detailInfo = Object.assign({}, res.data) // copy obj
      })
      this.dialogDetailVisible = true
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            id: this.rows.id,
            scenic_id: this.rows.scenic_id,
            name: this.rows.name,
            //  image: this.rows.image,
            isshow: this.rows.isshow,
            status: this.rows.status,
            jump_url: this.rows.jump_url,
            sort: this.rows.sort
          }
          edit(tempData).then((res) => {
            that.dialogFormVisible = false
            that.getList()
            notifySuccess(res.msg || '编辑成功')
          })
        }
      })
    }, // 导出EXCEL
    async handleExpload() {
      console.log(this.excelType)
      this.downloadLoading = true
      const that = this
      let templateList = Object.assign(that.list)
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.excelType === 2) {
        const tempQuery = Object.assign(that.listQuery)
        tempQuery.page = 1
        tempQuery.per_page = this.total
        await search(tempQuery).then((response) => {
          templateList = response.data.data
        })
      }
      loading.close()
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['序号', '景区ID', '景区名称', '是否显示']
        const filterVal = ['id', 'scenic_id', 'name', 'isshow_name']
        const data = that.formatJson(filterVal, templateList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
<style scoped >
.fideselect /deep/  .el-input__inner {
  background-color: #66b1ff;
  color: #fff;
}
.fideselect /deep/  .el-input__inner::placeholder {
  color: #fff;
}
</style>
